<template>
    <el-button @click="download" :text="elButtonIsText" :bg="elButtonIsBg" :type="elButtonType" :size="elButtonSize">
        {{ text }}
    </el-button>


    <!-- 根据dialog 的选择构建 excelDataVo -->
    <el-dialog :append-to-body="true" v-model="visible" :title="dialogTitle" class="text-center dialog">

        <CustomForm class="w-100" @submit="submit" :dialog-visible="visible" @update:dialog-visible="visible = $event"
            :field-list="fieldList">
            <template #exportWay>
                <div style="margin-bottom:20px">
                    <el-radio-group v-model="way" @change="wayChange">
                        <el-radio :label="1">导出所有数据</el-radio>
                        <el-radio :label="2">导出选中数据</el-radio>
                    </el-radio-group>
                </div>
            </template>

            <template #exportField>
                <div class="custom-tree-node-container">
                    <el-tree  class="w-100" ref="treeRef" :data="dataTree" show-checkbox node-key="id" default-expand-all
                        :expand-on-click-node="false" :props="{ class: customNodeClass }" />
                </div>
            </template>

        </CustomForm>

    </el-dialog>


</template>
    
<script setup lang='ts'>

import { ElButton, ElMessage, ElTree } from 'element-plus';
import CustomForm from '@/components/common/form/CustomForm.vue'
import { ComponentInternalInstance, getCurrentInstance, onMounted, PropType, ref, watch } from 'vue'
import * as _ from 'lodash'
import { useDownload } from '@/hook/useDownload'
import { useExcelSurveyDataFields } from '@/hook/useExcelSurveyDataFields'
import type { TreeNodeData } from 'element-plus/es/components/tree/src/tree.type';
import type Node from 'element-plus/es/components/tree/src/model/node';
import API from '@/network/api';
import { TemplateRVO,Field } from '@/hook/useRvo';

const proxy: any = (getCurrentInstance() as ComponentInternalInstance).proxy
const { downloadUrl } = useDownload()

const { drillHoleExportFieldList,
    insituTestExportFieldList,
    sampleExportList,
    stratumExportFieldList,
    waterExportFieldList,
    deviceExcelFieldList } = useExcelSurveyDataFields()

const props = defineProps({
    text: {
        type: String,
        default: ''
    },

    //excel的sheetName 
    sheetName: {
        type: String,
        default: ''
    },

    //下载类型  （excel模板 excel数据 excel复合数据）
    //excel模板不可选字段，excel数据导出可以选字段进行下载
    downloadType: {
        type: String as PropType<'TEMPLATE' | 'DATA' | 'DATAS' | 'REMOTE_URL'>,
        default: 'TEMPLATE'
    },

    //是否挂载表导出 已无单表导出 此属性废弃
    isCustom: {
        type: Boolean,
        default: false
    },

    //TEMPLATE 拿出所有数据的label 直接下载单行excel
    //DATA 依照字段获取单表excel数据
    fields: {
        type: Array<Field>,
        default: () => ([])
    },

    //选中的父id列表
    parentIds: {
        type: Object,
        default: () => ([])
    },

    //是否显示导出方式
    showExportWay: {
        type: Boolean,
        default: true
    },

    dialogTitle: {
        type: String,
        default:"导出Excel数据"
    },

    dataType: {
        type:String as PropType<'DRILL' | 'DEVICE'>,
        default:"DRILL"
    },

    elButtonIsText:{
        type:Boolean,
        default:false
    },
    elButtonIsBg:{
        type:Boolean,
        default:false
    },
    elButtonSize:{
        type:String as PropType<"" | "default" | "small" | "large">,
        default:"default"
    },
    elButtonType:{
        type:String as PropType<"" | "default" | "primary" | "success" | "warning" | "info" | "danger" | "text">,
        default:"default"
    },

    templateUrl:{
        type:String,
        default:""
    }

})

defineEmits(['update:fields', 'update:sheetName'])

// 数据相关vo
let dataVo = {


}


const visible = ref(false)


const download = async () => {


    let templateVo:TemplateRVO = {
        fields: props.fields,
        sheetName: props.sheetName
    }
    //下载模板情况  传入fields 直接下载
    if (props.downloadType == 'TEMPLATE') {
        let res = (await API.excel.template(templateVo))
        let vo = {
            key:res.singleData
        }
        let ossRes = await API.ossFile.url(vo);
        window.location.href = ossRes.singleData;
        
        // window.location.href = res.url;
        return;
    }

    //下载单表数据情况 暂无 2022年11月14日lu
    else if (props.downloadType == 'DATA') {
        visible.value = true
    }

    //下载多表数据情况 这里是 钻孔系列数据
    else if (props.downloadType == 'DATAS') {
        visible.value = true
    }

    else if (props.downloadType == 'REMOTE_URL'){


        console.log("props.downloadType == 'REMOTE_URL'")
        console.log(props.templateUrl)

        if(!_.isEmpty(props.templateUrl)){
            window.location.href = props.templateUrl;
        }
    }

    
}


const fieldList = ref([{
    name: "exportField",
    label: "导出字段",
    type: "SLOT"
}])

const checkList = ref([])
const exportTableListChange = () => { }

let customTableListVo = {
    pageSize: 300,
    pageNumber: 1,
    state: "lock",
    species: [] as String[]
}



/**
 * 导出excel data相关
 * 逻辑： 组合file数据组，而在后端 进行table层处理，进行sql拼接工作 
 */

onMounted(async () => {
    //获取 定义表和自定义表内容 填充 dataTree


    if(props.downloadType == 'DATA' && props.dataType == "DRILL"){
        dataTree.push(fieldListToTreeNode(1, "钻孔表", "drill_hole", drillHoleExportFieldList))
    }

    
    if (props.downloadType == 'DATAS' && props.dataType == "DRILL") {
        dataTree.push(fieldListToTreeNode(1, "钻孔表", "drill_hole", drillHoleExportFieldList))
        dataTree.push(fieldListToTreeNode(2, "原位试验表", "insitu_test", insituTestExportFieldList))
        dataTree.push(fieldListToTreeNode(3, "地层表", "stratum", stratumExportFieldList))
        dataTree.push(fieldListToTreeNode(4, "取样表", "sample", sampleExportList))
        dataTree.push(fieldListToTreeNode(5, "水位表", "water_level", waterExportFieldList))

        customTableListVo.species = ["DRILL_HOLE"]
        let customTables = (await proxy.$api.customTable.list(customTableListVo)).data.list

        for (let customTable of customTables) {
            let data = (await proxy.$api.customField.list4Fields(customTable.name)).data
            let tableFields = data.tableFields
            let tempList: any = []
            _.forEach(tableFields, el => {
                if (el.type == "TEXT" || el.type == "LONGTEXT") {
                    tempList.push(el);
                }
            })
            //加上钻孔编号
            let el = {
                name: "parent_code",
                label: "钻孔编号"
            }
            tempList.push(el);

            dataTree.push(fieldListToTreeNode(dataTree.length + 1, customTable.label, "drill_hole_" + customTable.name, tempList))
        }

        customTableListVo.species = ["DRILL_HOLE_N"]
        customTables = (await proxy.$api.customTable.list(customTableListVo)).data.list

        for (let customTable of customTables) {
            let data = (await proxy.$api.customField.list4Fields(customTable.name)).data
            let tableFields = data.tableFields
            let tempList: any = []
            _.forEach(tableFields, el => {
                if (el.type == "TEXT" || el.type == "LONGTEXT") {
                    tempList.push(el);
                }
            })
            //加上钻孔编号
            let el = {
                name: "parent_code",
                label: "钻孔编号"
            }
            tempList.push(el);

            dataTree.push(fieldListToTreeNode(dataTree.length + 1, customTable.label, "drill_hole_n_" + customTable.name, tempList))
        }
    }
    else if(props.downloadType == 'DATAS' && props.dataType == "DEVICE") {
        dataTree.push(fieldListToTreeNode(1, "设备表", "device", deviceExcelFieldList))
        customTableListVo.species = ["DEVICE"]
        let customTables = (await proxy.$api.customTable.list(customTableListVo)).data.list

        for (let customTable of customTables) {
            let data = (await proxy.$api.customField.list4Fields(customTable.name)).data
            let tableFields = data.tableFields
            let tempList: any = []
            _.forEach(tableFields, el => {
                if (el.type == "TEXT" || el.type == "LONGTEXT") {
                    tempList.push(el);
                }
            })
            //加上设备编号
            let el = {
                name: "parent_code",
                label: "设备编号"
            }
            tempList.push(el);

            dataTree.push(fieldListToTreeNode(dataTree.length + 1, customTable.label, "device_" + customTable.name, tempList))
        }

        customTableListVo.species = ["DEVICE_N"]
        customTables = (await proxy.$api.customTable.list(customTableListVo)).data.list

        for (let customTable of customTables) {
            let data = (await proxy.$api.customField.list4Fields(customTable.name)).data
            let tableFields = data.tableFields
            let tempList: any = []
            _.forEach(tableFields, el => {
                if (el.type == "TEXT" || el.type == "LONGTEXT") {
                    tempList.push(el);
                }
            })
            //加上设备编号
            let el = {
                name: "parent_code",
                label: "设备编号"
            }
            tempList.push(el);

            dataTree.push(fieldListToTreeNode(dataTree.length + 1, customTable.label, "device_n_" + customTable.name, tempList))
        }
    }

    if (props.showExportWay) {
        let item = {
            name: "exportWay",
            label: "导出方式",
            type: "SLOT"
        }
        fieldList.value.unshift(item)

        
    }else{
        //如果没有导出方式，那么 默认导出所有数据
        way.value = 1;
    }

})

/**
 * 
 */
const fieldListToTreeNode = (serial: number, label: string, tableName: string, list: Array<Object>) => {
    let id = serial * 100
    let tree: Tree = {
        id: id++,
        label: label,
        tableName: tableName,
        isPenultimate: true,
        children: []
    }

    _.forEach(list, (el: any) => {
        let leaf: Tree = {
            id: id++,
            label: el.label,
            isPenultimate: false,
            name: el.name
        }
        tree.children?.push(leaf);
    })

    return tree
}

const way = ref(2)
const wayChange = () => {
}

let templateVos: Array<TemplateVo> = []

interface TemplateVo {
    tableName: string
    fields: Array<Object>
    sheetName?: string
}

const submit = async () => {
    templateVos = []
    let checkedList = treeRef.value!.getCheckedNodes(false, true)

    let sortCheckedList = _.sortBy(checkedList, (o) => { return o.id })
    _.forEach(sortCheckedList, (el: any) => {

        if (el.id % 100 == 0) {
            let templateVo: TemplateVo = {
                tableName: el.tableName,
                fields: [],
                sheetName: el.label
            }
            templateVos.push(templateVo)
        } else {
            let field = {
                name: el.name,
                label: el.label
            }
            templateVos[templateVos.length - 1].fields.push(field)
        }
    })


    let ExcelDataVo = {
        templateVos: templateVos,
        projectOrParent: true,
        parentIds: []
    }

    //判断如何导出
    if (way.value != 1) {
        ExcelDataVo.projectOrParent = false
        ExcelDataVo.parentIds = props.parentIds as any

        if (_.isEmpty(ExcelDataVo.parentIds)) {
            ElMessage.warning("未选中任何钻孔！")
            return;
        }
    }

    let filename = (await proxy.$api.customTable.excelData(ExcelDataVo)).data.filename
    window.location.href = downloadUrl.value + filename;
}

/**
 * tableName 表名 //非叶节点使用
 * name 字段名  //叶节点使用
 */
interface Tree {
    id: number
    label: string
    tableName?: string
    name?: string
    isPenultimate?: boolean
    children?: Tree[]
}

const customNodeClass = (data: TreeNodeData, node: Node) => {
    if (data.isPenultimate) {
        return 'is-penultimate' as string
    }
    return "" as string
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const dataTree: Tree[] = []




</script>
    
<style scoped>
.custom-tree-node-container>>>.is-penultimate .el-tree-node__children {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.custom-tree-node-container>>>.is-penultimate .el-tree-node__children div {
    width: 16%;
}
</style>